package com.study.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
 * swagger配置类
 *
 * @author xupt
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    /**
     * 重点说明:
     * 其余都是可以默认,但是controller扫描的路径一定要改对,是该项目的controller包路径
     */
    public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.study.controller";
    /**
     * 前端传入的token名字
     */
    public static final String TOKEN_NAME = "x-token";

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //用户swagger上提交的byte类型数据矫正
                .directModelSubstitute(Byte.class, Integer.class)
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    /**
     * 下面两个方法主要是用于Authorization认证
     * @return
     */
    private List<ApiKey> securitySchemes() {
        return newArrayList(
                new ApiKey(TOKEN_NAME, TOKEN_NAME, "header"));
    }

    private List<SecurityContext> securityContexts() {
        return newArrayList(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.any())
                        .build()
        );
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return newArrayList(
                new SecurityReference(TOKEN_NAME, authorizationScopes));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("系统接口文档")
                .description("在线测试")
                .contact(new Contact("Xupt", "#", "miniprogram@88.com"))
                .version("1.0")
                .build();
    }
}
